package com.example.controller;

import com.example.common.RequirePermission;
import com.example.common.Result;
import com.example.service.MenuPermissionMappingService;
import com.example.service.PermissionInitService;
import com.example.service.PermissionService;
import com.example.util.UserContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 权限测试控制器
 * 用于测试权限分配是否正常工作
 */
@RestController
@RequestMapping("/api/permission-test")
@CrossOrigin
public class PermissionTestController {
    
    @Autowired
    private PermissionService permissionService;
    
    @Autowired
    private PermissionInitService permissionInitService;
    
    @Autowired
    private UserContextUtil userContextUtil;
    
    /**
     * 测试用户基础权限
     */
    @GetMapping("/user-permissions")
    public Result<Map<String, Object>> testUserPermissions() {
        Long userId = userContextUtil.getCurrentUserId();
        if (userId == null) {
            return Result.error("用户未登录");
        }
        
        List<String> permissions = permissionService.getUserPermissions(userId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("userId", userId);
        result.put("permissions", permissions);
        result.put("hasProfileView", permissions.contains("user:profile:view"));
        result.put("hasProfileEdit", permissions.contains("user:profile:edit"));
        result.put("hasPasswordChange", permissions.contains("user:password:change"));
        
        return Result.success(result);
    }
    
    /**
     * 重新初始化权限
     */
    @PostMapping("/reinit-permissions")
    @RequirePermission("admin:system:init")
    public Result<String> reinitPermissions() {
        try {
            permissionInitService.initializeBasicPermissions();
            return Result.success("权限重新初始化成功");
        } catch (Exception e) {
            return Result.error("权限初始化失败：" + e.getMessage());
        }
    }
    
    /**
     * 为当前用户创建基础权限
     */
    @PostMapping("/create-basic-permissions")
    public Result<String> createBasicPermissions() {
        Long userId = userContextUtil.getCurrentUserId();
        if (userId == null) {
            return Result.error("用户未登录");
        }
        
        try {
            permissionInitService.createBasicUserPermissions(userId);
            return Result.success("基础权限创建成功");
        } catch (Exception e) {
            return Result.error("基础权限创建失败：" + e.getMessage());
        }
    }
    
    /**
     * 测试个人中心权限
     */
    @GetMapping("/test-profile")
    @RequirePermission("user:profile:view")
    public Result<String> testProfile() {
        return Result.success("个人中心权限测试通过");
    }
}
